<template>
  <a-modal
    title="课程分类选择"
    :width="900"
    v-model:visible="visible"
    @ok="handleOk"
  >
    <div class="modal-body">
      <div class="modal-body-tree">
        <a-input-search
          style="margin-bottom: 8px"
          v-model="searchKey"
          placeholder="输入课程分类名称"
        />
        <a-tree
          :field-names="{ key: 'id', title: 'classifyName' }"
          :data="props.classifyTree"
          @select="select"
        ></a-tree>
      </div>
      <div class="modal-body-main">
        <div class="name">
          <div v-if="selectItem.node.classifyName" class="class-name">
            <span class="text"> {{ selectItem.node.classifyName }} </span>
            <icon-close class="icon" @click="del" />
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { isArray } from 'lodash';

const props = withDefaults(
  defineProps<{
    defaultValue?: number[] | number; //默认参数
    classifyTree: any;
  }>(),
  {
    defaultValue: 0
  }
);
const searchKey = ref('');
const emit = defineEmits(['handleOk']);
const select = (selectedKeys: any, data: any) => {
  selectItem.node = data.node;
};

const selectItem = reactive({ node: { classifyName: '' } });

//控制弹出框
const visible = ref(false);
watch(visible, (val) => {
  if (val) {
    const getSelectNode = (tree: any[]) => {
      if (isArray(tree)) {
        tree.forEach((element: any) => {
          if (element.id === props.defaultValue) {
            selectItem.node.classifyName = element.classifyName;
          }
          getSelectNode(element.children);
        });
      }
    };
    getSelectNode(props.classifyTree);
  }
});
defineExpose({ visible });

const handleOk = () => {
  emit('handleOk', selectItem.node);
};
const del = () => {
  selectItem.node.classifyName = '';
};
</script>

<style scoped lang="less">
.modal-body {
  display: flex;
  &-tree {
    height: 500px;
    overflow-x: hidden;
    border-right: 1px solid var(--color-fill-3);
    padding-right: 10px;
  }
  &-main {
    flex: 1;
    padding: 16px;
    .name {
      font-size: 24px;
      display: flex;
      .class-name {
        background: #eee;
        border-radius: 5px;
        padding: 8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .text {
          margin-right: 16px;
        }
        .icon {
          cursor: pointer;
        }
      }
    }
  }
}
</style>
